<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item
          :label="t('article.channelName')"
          prop="channelName"
          :class="store.appLocale == 'en_US' ? 'break-label' : ''"
        >
          <el-input v-model="formSearch.channelName" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('article.title')" prop="title">
          <el-input v-model="formSearch.title" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('article.author')" prop="author">
          <el-input v-model="formSearch.author" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('article.sourceName')" prop="sourceName">
          <el-input v-model="formSearch.sourceName" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('article.tags')" prop="tags">
          <el-input v-model="formSearch.tags" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('article.status')" prop="status">
          <el-select v-model="formSearch.status" clearable>
            <el-option :label="t('article.statusDraft')" value="0"></el-option>
            <el-option
              :label="t('article.statusPublished')"
              value="1"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('common.startDate')" prop="createTimeBegin">
          <el-date-picker
            v-model="formSearch.createTimeBegin"
            type="datetime"
            :shortcuts="shortcuts"
            clearable
            class="fix-el-date-picker-width"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('common.to')" prop="createTimeEnd">
          <el-date-picker
            v-model="formSearch.createTimeEnd"
            type="datetime"
            :shortcuts="shortcuts"
            clearable
            class="fix-el-date-picker-width"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>

      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button :icon="Search" type="primary" @click="handleSearch">{{
            t("common.searchButton")
          }}</el-button>
          <el-button :icon="RefreshLeft" @click="handleResetFields">{{
            t("common.resetButton")
          }}</el-button>
          <search-input-expland
            @on-expland-change="(v:boolean)=>{ searchInputExpland=v}"
          ></search-input-expland>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="admin-article-grid"
    row-key="articleId"
    defaultSort="descending"
    defaultSortBy="createTime"
    :request="handleLoadGrid"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <el-button size="mini" type="primary" :icon="Plus" @click="handleAdd">{{
        t("article.newArticle")
      }}</el-button>
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 account 仅在当前作用域有效 -->
    <template #topIndex="slotProps">
      <el-tag size="small" type="info" v-if="slotProps.row.topIndex == 0">
        {{ t("common.false") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.topIndex > 0">
        {{ t("common.true") }}</el-tag
      >
      &nbsp;
      <el-tag
        size="small"
        type="info"
        effect="light"
        v-if="slotProps.row.topIndex > 0"
      >
        {{ slotProps.row.topIndex }}
      </el-tag>
    </template>

    <template #tags="slotProps">
      <el-space
        :wrap="true"
        :size="10"
        alignment="left"
        v-if="slotProps.row.tags.length > 0"
      >
        <el-tag size="small" v-for="tag in slotProps.row.tags.split(',')">
          {{ tag }}</el-tag
        >
      </el-space>
    </template>

    <template #status="slotProps">
      <el-tag size="small" v-if="slotProps.row.status == 0" type="warning">
        {{ t("article.statusDraft") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.status == 1">
        {{ t("article.statusPublished") }}</el-tag
      >
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 operate 仅在当前作用域有效 -->
    <template #operate="slotProps">
      <el-link type="primary" @click="handleEdit(slotProps.row)">{{
        t("common.editButton")
      }}</el-link>
      &nbsp;
      <el-link
        type="primary"
        :title="slotProps.item.title"
        @click="handleDelete(slotProps.row)"
        >{{ t("common.deleteButton") }}
      </el-link>
    </template>
  </data-grid>
  <edit-form ref="editFormRef" @on-submit-success="onSubmitSuccess"></edit-form>
  <view-form ref="viewFormRef"></view-form>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import EditForm from "./edit.vue";
import ViewForm from "./view.vue";
import SearchInputExpland from "@/components/SearchInputExpland.vue";
import { Plus, Search, RefreshLeft } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import utils from "../../../utils/utils";
import apiCms from "../api/cms";
import { useStore } from "../../../stores/store";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
const store = useStore();
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const editFormRef = ref();
const viewFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);

// 查询区域表单数据
const formSearch = reactive({
  channelName: "",
  title: "",
  author: "",
  sourceName: "",
  tags: "",
  status: "",
  createTimeBegin: <Date>(<any>null),
  createTimeEnd: <Date>(<any>null),
});

const shortcuts = [
  {
    text: t("common.aWeekAgo"),
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      formSearch.createTimeBegin = start;
      formSearch.createTimeEnd = end;
      // return [start, end];
    },
  },
  {
    text: t("common.lastMonth"),
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      formSearch.createTimeBegin = start;
      formSearch.createTimeEnd = end;
      // return [start, end];
    },
  },
  {
    text: t("common.last3Months"),
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      formSearch.createTimeBegin = start;
      formSearch.createTimeEnd = end;
      // return [start, end];
    },
  },
];
const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      title: () => t("article.channelName"),
      field: "channelName",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: () => t("article.title"),
      field: "title",
      sortable: false,
      resizable: true,
    },
    {
      title: () => t("article.author"),
      field: "author",
      sortable: true,
      resizable: true,
      width: 120,
    },
    {
      title: () => t("article.sourceName"),
      field: "sourceName",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: () => t("article.topIndex"),
      field: "topIndex",
      sortable: true,
      resizable: true,
      width: 130,
      tdSlot: "topIndex",
    },
    {
      title: () => t("article.tags"),
      field: "tags",
      sortable: false,
      resizable: true,
      width: 200,
      tdSlot: "tags",
    },
    {
      title: () => t("article.status"),
      field: "status",
      sortable: true,
      resizable: true,
      tdSlot: "status",
      width: 100,
    },
    {
      title: () => t("organization.orgName"),
      field: "orgName",
      sortable: true,
      resizable: true,
      hidden: true,
      width: 120,
    },
    {
      title: () => t("article.publicationDate"),
      field: "publicationDate",
      sortable: true,
      resizable: true,
      hidden: true,
      width: 180,
    },
    {
      title: () => t("common.operateButton"),
      field: "opId",
      tdSlot: "operate",
      width: 150,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // params 是从表格组件接收的，包含分页和搜索字段，需要补充 query 查询条件信息
  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiCms
    .queryArticleListing(params)
    .then((response: any) => {
      data = response.data;
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
  // 返回数据给表格组件
  return data;
};

// 删除操作事件
const handleDelete = (row: any) => {
  // 从表格每行右侧链接点击触发的情况
  ElMessageBox.confirm(t("article.confirmDelete", { title: row.title }), {
    confirmButtonText: t("common.okButton"),
    cancelButtonText: t("common.cancelButton"),
  })
    .then(() => {
      apiCms
        .deleteArticle(row.articleId)
        .then((response: any) => {
          if (response.data.code == 200) {
            handleSearch();
            utils.infoNotification(t("article.deleted", { title: row.title }));
          }
        })
        .catch((err: any) => {
          utils.errorNotification(t("common.submitException"), err);
        });
    })
    .catch((err: any) => {});
};

// 打开新增页
const handleAdd = () => {
  editFormRef.value.show();
};
// 打开编辑页
const handleEdit = async (row: any) => {
  editFormRef.value.show(row);
};
// 新增、编辑页确定按钮操作成功回调事件
const onSubmitSuccess = (row: any) => {
  handleSearch();
};
// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
const handleResetFields = () => {
  formSearchRef.value.resetFields();
};
</script>
<style></style>
